#include <syslog.h>
#define NETDISK_LOG_INFO(net_fd, clientAddr) \
    do { \
        syslog(LOG_INFO, "1 client connected, fd = %d, ip = %s, port = %hu\n", net_fd, inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port)); \
    } while (0)
    

#define NETDISK_LOG_ERR(ret, err) { \
    if(ret == err) { \
        syslog(LOG_ERR, "an error occurred in %s:%s:%d\n", __FILE__, __FUNCTION__, __LINE__); \
    } \
}
#include "threadPool.h"

int main(int argc, char *argv[])
{
	// ./server ip 端口号 子线程数目
	ARGS_CHECK(argc, 4);
	char *ip = argv[1];
	char *port = argv[2];
	int threadNum = atoi(argv[3]);

	threadPool_t threadPool;
	// 初始化线程池和任务队列
	initThreadPool(&threadPool, threadNum); // initThreadPool.c

	int socket_fd;
	// 初始化socket连接
	initTcpSocket(&socket_fd, ip, port);

	int epoll_fd = epoll_create(1);
	// 添加socket_fd到epoll
	epollAddFD(epoll_fd, socket_fd);

	// 用来获取客户端的地址信息
	struct sockaddr_in clientAddr;
	// 客户端地址信息结构体大小
	socklen_t clientAddrLength = sizeof(clientAddr);
	struct epoll_event readyset[1024];
	while (1)
	{
		int readynum = epoll_wait(epoll_fd, readyset, 1024, -1);
		for (int i = 0; i < readynum; ++i)
		{
			if (readyset[i].data.fd == socket_fd)
			{
				int net_fd = accept(socket_fd, (struct sockaddr *)&clientAddr, &clientAddrLength);
				NETDISK_LOG_INFO(net_fd, clientAddr);
				pthread_mutex_lock(&threadPool.taskQueue.mutex);
				enQueue(&threadPool.taskQueue, net_fd);
				pthread_cond_signal(&threadPool.taskQueue.cond);
				pthread_mutex_unlock(&threadPool.taskQueue.mutex);
			}
		}
	}

	close(epoll_fd);
	close(socket_fd);

	return 0;
}